from PIL import Image, ImageFilter
import os

def increase_image_size_to_target(input_image_path, output_image_path, target_size_mb, scale_factor=3.0, quality=95):
    # 打开图片
    with Image.open(input_image_path) as img:
        # 初始图片大小
        original_size = os.path.getsize(input_image_path) / (1024 * 1024)
        print(f"Original size: {original_size:.2f} MB")

        # 增加分辨率
        width, height = img.size
        new_width = int(width * scale_factor)
        new_height = int(height * scale_factor)
        img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

        # 添加一些噪声或模糊处理（这将增加文件的复杂度，影响文件大小）
        img_resized = img_resized.filter(ImageFilter.GaussianBlur(0.5))

        # 保存为无损格式（如 PNG）来增大文件大小
        current_size = original_size
        while current_size < target_size_mb:
            img_resized.save(output_image_path, 'PNG')  # 尝试使用无损格式
            current_size = os.path.getsize(output_image_path) / (1024 * 1024)
            print(f"Current size: {current_size:.2f} MB")

            # 如果文件大小仍不足，进一步增大图片的分辨率
            if current_size < target_size_mb:
                scale_factor += 0.5
                new_width = int(width * scale_factor)
                new_height = int(height * scale_factor)
                img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
                img_resized = img_resized.filter(ImageFilter.GaussianBlur(0.5))

        print(f"Final size: {current_size:.2f} MB, Resolution: {new_width}x{new_height}")

# 示例用法
input_path = "C:/Users/35658/Desktop/IMG_20241006_143135.jpg"  # 原始图片路径
output_path = 'C:/Users/35658/Desktop/competition/红旗摄影/信院计科23-3汪钰轩202311040071《时光映红，岁月不朽》3.png'      # 增大后的图片路径
target_size_mb = 3.0                    # 目标大小（MB）
scale_factor = 3.0                      # 初始放大倍数

increase_image_size_to_target(input_path, output_path, target_size_mb, scale_factor)
